<template>
  <div class="message-page">
    <div class="message-top-box">
      <div class="message-types">
        <div v-for="(item, index) in messageList" :key="index"
          :class="['message-type-item', currentMessage.value == item.value && 'active']" @click="changeMessage(item)">
          {{ $t(item.label) }}
        </div>
      </div>
      <el-button type="primary" @click="doAction('add')">
        <svg class="add-icon">
          <use xlink:href="#keowledge-xinjian"></use>
        </svg>
        {{ $t('message.text.addNewTemplate') }}
      </el-button>
    </div>
    <div class="message-tips">{{ $t(currentMessage.desc) }}</div>
    <el-table :data="tableData" header-row-class-name='table-header-class' v-loading="tableLoading"
      style="height:calc(100% - 124px)">
      <el-table-column prop="name" :label="$t('message.table.templateName')"></el-table-column>
      <el-table-column prop="createBy" :label="$t('message.table.createBy')">
      </el-table-column>
      <el-table-column prop="createTime" :label="$t('message.table.createTime')" />
      <el-table-column :label="$t('message.table.operation')" width="120px">
        <template #default="scope">
          <div class="actions">
            <el-button type="text"
              @click="doAction('edit', scope.row, scope.$index)">{{ $t('message.buttons.edit') }}</el-button>
            <div class="line"></div>
            <el-button type="text" class="button-danger"
              @click="doAction('del', scope.row)">{{ $t('message.buttons.delete') }}</el-button>
          </div>
        </template>
      </el-table-column>
      <template #empty>
        <jvs-empty></jvs-empty>
      </template>
    </el-table>
    <div class="page-box">
      <el-pagination background layout="prev, pager, next" :total="pageObj.total" :page-size="pageObj.size"
        v-model:current-page="pageObj.current" @current-change="handleCurrentChange" />
    </div>
  </div>
  <el-dialog v-model="messageAddVisible" class="custom-dialog" width="766px" :show-close='false'
    :close-on-click-modal="false" modal-class="dialog-center" :before-close="handleClose">
    <div class="custom-dialog-header">
      <div class="title-box">
        <div class="title">
          {{ messageType == 'add' ? `${$t('message.add')}${$t(currentMessage.label)}` : `${$t('message.buttons.edit')}${$t(currentMessage.label)}` }}
        </div>
      </div>
      <svg class="close-icon" @click="handleClose">
        <use xlink:href="#keowledge-danchuangguanbi1"></use>
      </svg>
    </div>
    <div class="custom-dialog-body">
      <el-form :model="messageForm" :rules="messageRules" size="large" ref="messageFormRef">
        <el-form-item prop="name">
          <div class="custom-form-title"><span class="require">*</span>{{ $t('message.table.templateName') }}</div>
          <el-input v-model="messageForm.name" :placeholder="$t('message.placeholder.pleaseTemplateName')" />
        </el-form-item>
        <el-form-item prop="code" v-if="['EMAIL', 'INSIDE'].indexOf(currentMessage.value) == -1">
          <div class="custom-form-title"><span
              class="require">*</span>{{ currentMessage.value == 'SMS' ? $t('message.form.templateCode') : $t('message.form.templateId') }}
          </div>
          <el-input v-model="messageForm.code"
            :placeholder="currentMessage.value == 'SMS' ? $t('message.form.templateCode') : $t('message.form.templateId')"
            :disabled="true" />
        </el-form-item>
        <el-form-item prop="signName" v-if="currentMessage.value == 'SMS'">
          <div class="custom-form-title"><span class="require">*</span>{{ $t('message.form.smsSignature') }}</div>
          <el-input v-model="messageForm.signName" :placeholder="$t('message.placeholder.smsSignature')" />
        </el-form-item>
        <el-form-item prop="code" v-if="['EMAIL', 'INSIDE'].indexOf(currentMessage.value) == -1">
          <div class="custom-form-title"><span class="require">*</span>{{ $t('message.form.selectTemplate') }}</div>
          <el-select v-model="messageForm.code" :placeholder="$t('message.placeholder.selectTemplate')"
            @change="codeChange">
            <el-option v-for="(item, index) in optionList" :key="index" :label="item.label" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="content">
          <div class="custom-form-title"><span class="require">*</span>{{ $t('message.form.templateContent') }}{{}}</div>
          <el-input v-model="messageForm.content" type="textarea"
            :placeholder="$t('message.placeholder.templateContent')" :autosize="{ minRows: 6, maxRows: 6 }"
            :disabled="['EMAIL', 'INSIDE'].indexOf(currentMessage.value) == -1" @input="handleInputChange"></el-input>
          <div class="content-tips" v-if="['EMAIL', 'INSIDE'].indexOf(currentMessage.value) != -1">
            <img src="../../assets/images/info.png">
            <span>{{ $t('message.text.templateVariable') }}{{ currentMessage.value != 'WX_ENTERPRISE' ? getMessageTips('var') : getMessageTips('wx') }}</span>
          </div>
        </el-form-item>
        <el-form-item prop="tempLateList" v-if="messageForm.tempLateList.length > 0">
          <div class="custom-form-title"><span
              class="require">*</span>{{ ['EMAIL', 'INSIDE'].indexOf(currentMessage.value) == -1 ? $t('message.form.variableConfiguration') : $t('message.form.variableSet') }}
          </div>
          <div v-for="(item, index) in messageForm.tempLateList" :key="index" class="message-template-list-item">
            <div class="name">{{ item.name }}</div>
            <div class="select">
              <el-select v-model="item.value" :placeholder="$t('message.placeholder.bindField')">
                <el-option v-for="(vItem, vIndex) in variableList" :key="vIndex" :label="vItem.variableExplain"
                  :value="vItem.id"></el-option>
              </el-select>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="custom-dialog-footer">
        <el-button @click="handleClose">{{ $t('message.buttons.cancal') }}</el-button>
        <el-button type="primary" @click="handleSave">{{ $t('message.buttons.submit') }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  watch,
  onMounted,
  nextTick,
  getCurrentInstance
} from 'vue'

import { useRouter } from "vue-router"
import type { FormRules } from 'element-plus'
import {
  messageInsidePage, messageSmsPage, messageEmailPage, messageInsideUpdate, messageInsideDel, getWxmpTemplateList, getSmsTemplateList,
  messageSmsAdd, messageSmsDel, messageEmailAdd, messageEmailDel, messageWxPage, messageWxupdate, messageWxDel, messageWxById, messageVarSelect,
  messageGetVar,
} from '@/api/message'
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const router = useRouter();

const emit = defineEmits([""])
const { proxy } = getCurrentInstance()
const props = defineProps({})

const messageList = [
  {
    key: "",
    label: 'message.text.messageTemplate',
    value: 'INSIDE',
    desc: 'message.text.messageDesc',
    icon: 'el-icon-bell',
    show: true,
    num: 0,
  },
  {
    key: "",
    label: 'message.text.smsTemplate',
    value: 'SMS',
    desc: 'message.text.smsDesc',
    icon: 'el-icon-chat-round',
    show: false,
    num: 0,
  },
  {
    key: "",
    label: 'message.text.emailTemplate',
    value: 'EMAIL',
    desc: 'message.text.emailDesc',
    icon: 'el-icon-message',
    show: false,
    num: 0,
  },
  {
    key: "",
    label: 'message.text.enterpriseTemplate',
    value: 'WX_ENTERPRISE',
    desc: 'message.text.wxEnterpriseDesc',
    icon: 'el-icon-microphone',
    show: false,
    num: 0,
  }
]
const currentMessage = ref({
  key: "",
  label: 'message.text.messageTemplate',
  value: 'INSIDE',
  desc: 'message.text.messageDesc',
  icon: 'el-icon-bell',
  show: true,
  num: 0,
})
const WX_ENTERPRISE = /{{([a-zA-Z0-9]*)\.DATA}}/g
const WECHAT_REGULAR = /{{([a-zA-Z0-9]*)\.DATA}}/
const DING_H5 = /\${([a-zA-Z0-9]*)}/g
const INSIDE_REGULAR = /\${([a-zA-Z0-9]*)}/
const reqPage = ref<any>(null)
const reqEdit = ref<any>(null)
const reqDel = ref<any>(null)

const tableLoading = ref(false)
const tableData = ref([])
const messageAddVisible = ref(false)
const messageType = ref('')
const messageIndex = ref(0)
const pageObj = ref({
  current: 1,
  size: 30,
  total: 0
})
const messageFormRef = ref()
const messageForm = ref({
  name: '',
  content: '',
  code: '',
  templateCode: '',
  wechatTemplateId: "",
  signName: '',
  tempLateList: []
})
const messageRules = ref<FormRules>({
  name: [{
    validator: (rule: any, value: any, callback: any) => {
      if (!value) {
        callback(new Error($t('message.placeholder.pleaseTemplateName')))
      } else {
        callback()
      }
    }
  }],
  content: [{
    validator: (rule: any, value: any, callback: any) => {
      if (!value) {
        if (['SMS', 'WX_ENTERPRISE'].indexOf(currentMessage.value.value) != -1) {
          callback(new Error($t('message.placeholder.checkTemplateContent')))
        } else {
          callback(new Error($t('message.placeholder.templateContent')))
        }
      } else {
        callback()
      }
    }
  }],
  code: [{
    validator: (rule: any, value: any, callback: any) => {
      if (!value) {
        callback(new Error(`${$t('message.placeholder.templateTitle')}${currentMessage.value.value == 'SMS' ? $t('message.placeholder.templaetCode') : $t('message.placeholder.templaetId')}`))
      } else {
        callback()
      }
    }
  }],
  signName: [{
    validator: (rule: any, value: any, callback: any) => {
      if (!value) {
        callback(new Error($t('message.placeholder.smsSignature')))
      } else {
        callback()
      }
    }
  }],
  tempLateList: [{
    validator: (rule: any, value: any, callback: any) => {
      let hasNull = false
      value.forEach(item => {
        if (!item.value) {
          hasNull = true
        }
      })
      if (hasNull) {
        let mes = ['EMAIL', 'INSIDE'].indexOf(currentMessage.value.value) == -1 ? $t('message.form.variableConfiguration') : $t('message.form.variableSet')
        callback(new Error(`${$t('message.placeholder.fillInAll')}${mes}`))
      } else {
        callback()
      }
    }
  }]
})
const optionList = ref([])
const variableList = ref<any[]>([])
const variableIdsList = ref<any[]>([])
const varListTemp = ref([])
onMounted(() => {
  reqPage.value = messageInsidePage
  reqEdit.value = messageInsideUpdate
  reqDel.value = messageInsideDel
  getMessageList()
  nextTick(() => {
    proxy.$eventBus.$emit('breadListChange', currentMessage.value.label)
  })
})
function changeMessage(item) {
  if (currentMessage.value.value != item.value) {
    pageObj.value.current = 1
    currentMessage.value = item
    switch (item.value) {
      // 站内
      case 'INSIDE':
        reqPage.value = messageInsidePage
        reqEdit.value = messageInsideUpdate
        reqDel.value = messageInsideDel
        break;
      // 短信
      case 'SMS':
        reqPage.value = messageSmsPage
        reqEdit.value = messageSmsAdd
        reqDel.value = messageSmsDel
        break;
      // 邮件
      case 'EMAIL':
        reqPage.value = messageEmailPage
        reqEdit.value = messageEmailAdd
        reqDel.value = messageEmailDel
        break;
      // 微信
      case 'WX_ENTERPRISE':
        reqPage.value = messageWxPage
        reqEdit.value = messageWxupdate
        reqDel.value = messageWxDel
        break;
      default:
        break;
    }
    proxy.$eventBus.$emit('breadListChange', currentMessage.value.label)
    getMessageList()
  }
}
// 
function getMessageList() {
  if (!reqPage.value) return
  tableLoading.value = true
  reqPage.value({
    size: pageObj.value.size,
    current: pageObj.value.current
  }).then(res => {
    if (res.data.code == 0) {
      tableData.value = res.data.data.records
      pageObj.value.total = res.data.data.total
      tableLoading.value = false
    }
  })
}
function doAction(type, row, index) {
  messageType.value = type
  messageIndex.value = index
  switch (type) {
    case 'del':
      proxy.$confirm($t('message.confirm.delTmeplate'), $t('message.prompt'), {
        confirmButtonText: $t('message.buttons.submit'),
        cancelButtonText: $t('message.buttons.cancal'),
        type: 'warning'
      }).then(() => {
        reqDel.value(row.id).then(res => {
          if (res.data.code == 0) {
            getMessageList()
          }
        })
      })
      break;
    case 'edit':
      messageForm.value = JSON.parse(JSON.stringify(row))
      if (['SMS', 'WX_ENTERPRISE'].indexOf(currentMessage.value.value) != -1) {
        messageForm.value.code = row.wechatTemplateId || row.templateCode
      }
      messageForm.value.tempLateList = []
      getDetail(row)
    case 'add':
      getEventList()
      if (['SMS', 'WX_ENTERPRISE'].indexOf(currentMessage.value.value) != -1) {
        getTemplateList()
      }
      messageAddVisible.value = true
      break
    default:
      break;
  }
}
async function getDetail(item) {
  let resMessage = await messageGetVar(item.id)
  if (resMessage.data && resMessage.data.code == 0) {
    let listArr = []
    resMessage.data.data.forEach((item, index) => {
      if (listArr.indexOf(item.messageVariableName) == -1) {
        listArr.push(item.messageVariableName)
        messageForm.value.tempLateList.push({
          id: item.id,
          name: item.messageVariableName,
          value: item.variableId
        })
      }
    })
  }
}
function handleCurrentChange() {
  getMessageList()
}
function handleSave() {
  messageFormRef.value.validate(valid => {
    if (valid) {
      // 添加binDingList
      let binDingList = []
      messageForm.value.tempLateList.forEach((item, index) => {
        let bindingItem = variableList.value[variableIdsList.value.indexOf(item.value)]
        binDingList.push({
          messageVariableName: item.name,
          variableExplain: bindingItem.variableExplain,
          variableId: item.value,
          variableName: bindingItem.variableName
        })
      })
      let obj = {}
      if (currentMessage.value.value == 'SMS') {
        obj.templateCode = messageForm.value.code
      }
      if (currentMessage.value.value == 'WX_ENTERPRISE') {
        obj.wechatTemplateId = messageForm.value.code
      }
      reqEdit.value({
        binDingList: binDingList,
        ...messageForm.value,
        ...obj,
      }).then(res => {
        if (res.data.code == 0) {
          if (messageType.value == 'edit') {
            tableData.value[messageIndex.value].name = messageForm.value.name
            if (currentMessage.value.value == 'SMS') {
              tableData.value[messageIndex.value].signName = messageForm.value.signName
              tableData.value[messageIndex.value].templateCode = messageForm.value.code
            }
            if (currentMessage.value.value == 'WX_ENTERPRISE') {
              tableData.value[messageIndex.value].wechatTemplateId = messageForm.value.code
            }
          } else {
            getMessageList()
          }
          handleClose()
        }
      })
    }
  })
}
function getTemplateList() {
  let fun = getWxmpTemplateList
  if (currentMessage.value.value == 'SMS') {
    fun = getSmsTemplateList
  }
  fun().then(res => {
    if (res.data.code == 0) {
      optionList.value = (res.data.data || []).filter(item => {
        item.label = item.templateName || item.title
        item.code = item.templateCode || item.templateId
        item.content = item.content || item.templateContent
        if (currentMessage.value.value == 'SMS') {
          return item.auditStatus === 'AUDIT_STATE_PASS'
        } else {
          return true
        }
      })
    }
  })
}
function handleClose() {
  messageForm.value = {
    name: '',
    content: '',
    code: '',
    templateCode: '',
    wechatTemplateId: "",
    signName: '',
    tempLateList: []
  }
  messageFormRef.value.resetFields()
  messageAddVisible.value = false
}
function codeChange() {
  optionList.value.forEach((item, index) => {
    if (item.code == messageForm.value.code) {
      messageForm.value.content = item.content
      messageForm.value.tempLateList = formatVariableListBySymbol(currentMessage.value.value == 'SMS' ? '${}' : '{{}}', messageForm.value.content)
    }
  })
}
// 获取事件列表
function getEventList() {
  messageVarSelect().then(res => {
    if (res.data && res.data.code == 0) {
      variableList.value = [...res.data.data] || []
      variableList.value.forEach((item, index) => {
        variableIdsList.value.push(item.id)
      })
    }
  })
}
function handleInputChange(e) {
  let regularAll: any, regular: any
  messageForm.value.tempLateList = []
  if (currentMessage.value.value === 'WX_ENTERPRISE') {
    regularAll = WX_ENTERPRISE
    regular = WECHAT_REGULAR
  } else {
    regularAll = DING_H5
    regular = INSIDE_REGULAR
  }
  const listTemp = varListTemp.value.map(item => {
    return item.name
  })
  let arr: any = []
  if (e.match(regularAll)) {
    e.match(regularAll).forEach(item => {
      if (item.match(regular)[1].length > 0) {
        const index = arr.findIndex(it => {
          return it.name === item.match(regular)[1]
        })
        if (index === -1) {
          arr.push({
            value: listTemp.indexOf(item.match(regular)[1]) > -1 ? varListTemp.value[listTemp.indexOf(item.match(regular)[1])].value : '',
            name: item.match(regular)[1]
          })
        }
      }
    })
    messageForm.value.tempLateList = arr
    varListTemp.value = messageForm.value.tempLateList
  } else {
    messageForm.value.tempLateList = []
    varListTemp.value = messageForm.value.tempLateList
  }
}
//获取变量集合处理方法
function formatVariableListBySymbol(symbol, content): any {
  // console.log(symbol, content)
  let regexp;
  let result = []
  if (symbol == '{{}}') {
    regexp = /\{{(.+?)\}}/g
    let vars = content.match(regexp)
    if (vars) {
      for (let v of vars) {
        let str = v
        if (v.includes('.')) {
          str = v.split('.')[0]
          str = str.slice(2)
        } else {
          str = str.slice(2, str.length - 2)
        }
        result.push({ name: str, value: '' })
      }
    }
  }
  if (symbol == '${}') {
    regexp = /\$\{(.+?)\}/g
    let vars = content.match(regexp)
    if (vars) {
      for (let v of vars) {
        let str = v
        if (v.includes('.')) {
          str = v.split('.')[0]
          str = str.slice(2)
        } else {
          str = str.slice(2, str.length - 1)
        }
        result.push({ name: str, value: '' })
      }
    }
  }
  return result
}
// const weChartInfo = $t('message.text.wxEnterpriseInfo')
// const defaultInfo = $t('message.text.varInfo')
function getMessageTips(type) {
  let str = '', tipArr: string[] = []
  if (type == 'var') {
    tipArr = ['message.text.varInfo']
  } else {
    tipArr = ['message.text.wxEnterpriseInfo']
  }
  console.log(tipArr, type)
  tipArr.map((item) => {
    console.log($t(item))
    str += $t(item)
  })
  return str.replaceAll('#2', '}').replaceAll('#1', '{')
}
</script>
<style lang="scss" scoped>
.message-page {
  padding: 8px 24px;
  height: calc(100% - 16px);

  .message-top-box {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .message-types {
      display: flex;
      align-items: center;
      height: 32px;

      .message-type-item {
        color: #6F7588;
        height: 32px;
        cursor: pointer;
        line-height: 32px;
      }

      .message-type-item+.message-type-item {
        margin-left: 32px;
      }

      .active {
        position: relative;
        @include SourceHanSansCN-Bold;
        color: #1E6FFF;

        &::after {
          content: '';
          position: absolute;
          width: 100%;
          height: 2px;
          background: #1E6FFF;
          border-radius: 2px 0px 2px 0px;
          bottom: 0px;
          left: 0px;
        }
      }
    }

    .add-icon {
      width: 14px;
      height: 14px;
      margin-right: 4px;
    }
  }

  .message-tips {
    font-size: 14px;
    color: #6F7588;
    margin: 16px 0px;
  }

  ::v-deep(.el-scrollbar__view) {
    height: 100%;
  }

  ::v-deep(.table-header-class) {
    color: #363B4c;
    @include SourceHanSansCN-Bold;
    font-size: 12px;
    background: #F5F6F7;

    th {
      background: #F5F6F7;
    }
  }

  .actions {
    display: flex;
    align-items: center;

    button {
      @include SourceHanSansCN-Regular;
    }

    .line {
      width: 1px;
      height: 14px;
      background: #EEEFF0;
      margin: 0px 8px;
    }

    .button-danger {
      color: #FF194C;
    }
  }

  .page-box {
    display: flex;
    justify-content: end;
    margin-top: 8px;
  }
}

.custom-dialog-body {
  padding: 24px 32px;

  .message-template-list-item {
    display: flex;
    align-items: center;
    width: 100%;
    border-radius: 4px;
    height: 36px;
    overflow: hidden;
    background: #F5F6F7;

    ::v-deep(input) {
      height: 34px;
      line-height: 34px;
    }

    .name {
      background-color: #EEEFF0;
      width: 160px;
      padding: 0px 12px;
    }

    .select {
      width: 100%;
      display: flex;
      align-items: center;
    }
  }

  .is-error {
    .message-template-list-item {
      ::v-deep(.is-focus) {
        .el-input__wrapper {
          box-shadow: none !important;
        }
      }

      ::v-deep(.is-focus, .el-input__wrapper) {
        box-shadow: none !important;
      }
    }
  }

  .message-template-list-item+.message-template-list-item {
    margin-top: 6px;
  }

  .content-tips {
    display: flex;
    align-items: center;
    height: 24px;
    line-height: 24px;

    img {
      width: 16px;
      height: 16px;
      margin-right: 4px;
      font-size: 14px;
    }

    span {
      color: #1E6FFF;
    }
  }
}
</style>